package com.craftsman.tomcat.nio;

import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.http.*;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;

import java.io.UnsupportedEncodingException;
import java.util.Objects;


@Data
@NoArgsConstructor
@AllArgsConstructor
public class BXNIOResponse {

    private ChannelHandlerContext context;

    private HttpRequest request;


    public void write(String out)throws Exception{
        try {
            if(Objects.isNull(out) || out.length()==0){
                return ;
            }
            FullHttpResponse response=new DefaultFullHttpResponse(
              //设置版本http 1.1
              HttpVersion.HTTP_1_1,
              HttpResponseStatus.OK,
              Unpooled.wrappedBuffer(out.getBytes("utf-8"))
            );
            response.headers().set("Content-Type","text/html");
            context.write(response);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            context.flush();
            context.close();
        }
    }

}
